package com.demo.chapter7parallel;

import java.util.function.Function;
import java.util.stream.LongStream;
import java.util.stream.Stream;

/**
 * 错误的并行流使用方式
 * 
 * @author Administrator
 *
 */
public class WrongParallelStreams {

	public static long sideEffectParallelSum(long n) {
        Accumulator accumulator = new Accumulator();
        LongStream.rangeClosed(1, n).parallel().forEach(accumulator::add);
        return accumulator.total;
    }

    public static class Accumulator {
        private long total = 0;

        public void add(long value) {
            total += value;
        }
    }
    
    public static void main(String[] args) {
    	for(int i=0; i<10; i++){
    		//每次结果都不一样，因为Accumulator函数是有副作用的，它会改变多个线程共享的对象的可变状态total
    		System.out.println(sideEffectParallelSum(1000));
    	}
	}

}
